package com.gsma.calendar.android.ui;

import java.text.ParseException;
import java.util.Date;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.TextView;

import com.gsma.calendar.android.R;
import com.gsma.calendar.android.db.GlobalEventColumns;
import com.gsma.calendar.android.db.GlobalEventQuery;
import com.gsma.calendar.android.model.GlobalEvent;
import com.gsma.calendar.android.util.Config;

public class GlobalEventDetail extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

	private TextView header_info;
	private TextView overview_value;
	private String eventName;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.global_event_detail);

		header_info = (TextView) findViewById(R.id.header_info);
		overview_value = (TextView) findViewById(R.id.overview_value);

		String event = getIntent().getStringExtra(Config.EVENT);
		Bundle bundleLoader = new Bundle();
		bundleLoader.putString(Config.EVENT, event);
		getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, bundleLoader, this);

	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case GlobalEventQuery._TOKEN:
			String event = bundle.getString(Config.EVENT);
			return new CursorLoader(GlobalEventDetail.this, GlobalEvent.CONTENT_URI, GlobalEventQuery.PROJECTION, GlobalEventColumns.EVENT.getName() + "=?",
					new String[] { event }, GlobalEvent.START_TIME_SORT);
		default:
			return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case GlobalEventQuery._TOKEN:
			if (cursor != null && cursor.moveToFirst()) {
				startManagingCursor(cursor);
				eventName = cursor.getString(GlobalEventQuery.EVENT);
				StringBuilder sb = new StringBuilder();
				sb.append(eventName);
				sb.append("\n Location: ");
				sb.append(cursor.getString(GlobalEventQuery.LOCATION));
				sb.append("\n Date: " + Config.sdf_full.format(new Date(cursor.getLong(GlobalEventQuery.START_TIME)))
						+ Config.sdf_full.format(new Date(cursor.getLong(GlobalEventQuery.END_TIME))));

				header_info.setText(sb.toString());
				overview_value.setText(cursor.getString(GlobalEventQuery.OVERVIEW));

			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

	public void openSubSchedule(View view) {
		Intent intent = new Intent(GlobalEventDetail.this, AgendaDaysActivity.class);
		intent.putExtra(Config.EVENT, eventName);
		startActivity(intent);
	}

}
